﻿using System.Collections.Generic;
using System.Linq;
using ATTools.Models;
using Orchard.Environment.Extensions;

namespace ATTools.Helpers
{
    [OrchardFeature("ATTools.VoiceCommands")]
    public static class JsonHelper
    {
        public static string CommandsToJson(IEnumerable<VoiceCommandRecord> commands)
        {
            var ret = "";
            if (commands != null)
            {
                ret = string.Join(",", from d in commands
                                           select MakeObject(new string[] {
                                           MakeProperty("command", d.Description.Trim()),
                                           MakeProperty("data", d.CommandData),
                                           MakeProperty("type", d.CommandType)
                                       }));
            }
            return "[" + ret + "]";
        }

        private static string MakeObject(string[] properties)
        {
            return "{" + string.Join(",", properties) + "}";
        }

        private static string MakeProperty(string name, int value)
        {
            return QuoteString(name) + ":" + value;
        }

        private static string MakeProperty(string name, string value)
        {
            return QuoteString(name) + ":" + QuoteString(EscapeString(value));
        }

        private static string QuoteString(string value)
        {
            return "\"" + value + "\"";
        }

        private static string EscapeString(string value)
        {
            return value.Replace("\b", "\\b").Replace("\t", "\\t").Replace("\n", "\\n")
                .Replace("\f", "\\f").Replace("\r", "\\r").Replace("\"", "\\\"");
        }
    }
}